package me.chan.sort;

import me.chan.util.SortUtil;

import static me.chan.util.SortUtil.less;

/**
 * Created by JanGin on 2017/9/10.
 */
public class MergeSort {

    private MergeSort(){}

    public static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {

        int i = lo, j = mid + 1;
        /*
        Comparable[] aux = new Comparable[a.length];
        for (int k = lo; k <= hi; k++) {
            aux[k] = a[k];
        }*/

        for (int k = lo; k <= hi; k ++) {
            if ( i > mid )
                a[k] = aux[j++];
            else if ( j > hi )
                a[k] = aux[i++];
            else if (less(aux[j], aux[i]))
                a[k] = aux[j++];
            else
                a[k] = aux[i++];
        }

    }






    public  static void sort(Comparable[]a, Comparable[] aux) {
        sort(a, aux, 0, a.length - 1);
    }

    private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
        if (hi <= lo) return;
        int mid = lo + (hi - lo)/2;
        sort(a, aux, lo, mid);
        sort(a, aux, mid + 1, hi);
        merge(a, aux, lo, mid, hi);
    }


    public static void sort2(Comparable[] a, Comparable[] aux) {
        int N = a.length;
        for (int sz=1; sz < N; sz += sz) {
            for (int lo = 0; lo < N - sz; lo += sz+sz) {
                merge(a, aux, lo, lo+sz-1, Math.min(lo+sz+sz-1, N-1));
            }
        }

    }

    public static void main(String[] args) {

        Comparable[] arr = {'E', 'E', 'G', 'M', 'R', 'A', 'C', 'E', 'R', 'T'};
        Comparable[] aux = new Comparable[arr.length];

        for (int i=0; i < aux.length; i++) {
            aux[i] = arr[i];
        }
        SortUtil.show(arr);
        sort(arr, aux);
        SortUtil.show(arr);
    }
}
